
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "esp_system.h"
#include "esp_event.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "nvs_flash.h"
#include "esp_sntp.h"
#include "BSP_WiFi.h"
#include "OLED_Task.h"


QueueHandle_t Time_synchronization_Queue_Handle = NULL;


void time_sync_notification_cb(struct timeval *tv)
{
    ESP_LOGI("sntp_Init", "Notification of a time synchronization event");
}


//初始SNTP连接
static void SNTP_Init(void)
{
       
    ESP_LOGI("sntp_Init", "Initializing SNTP");
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "pool.ntp.org");
    sntp_set_time_sync_notification_cb(time_sync_notification_cb);
    sntp_init();
}


//时间同步任务
void time_synchronization_Task(void*p)
{
    xEventGroupWaitBits(WiFi_EventGroupHandle, WIFI_CONNECT_SUCCESS, pdFALSE, pdFALSE, portMAX_DELAY);
    struct tm timeinfo = {0};
    time_t now = 0;
    char time_data[64];
    SNTP_Init();
    setenv("TZ", "CST-8", 1);
    tzset();

    while(1)
    {

      
        int retry = 0;
        const int retry_count = 10;
        // while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
        // ESP_LOGI("TAG", "Waiting for system time to be set... (%d/%d)", retry, retry_count);
        // vTaskDelay(100 / portTICK_PERIOD_MS);
        // }
        sntp_get_sync_status();
        time(&now);
        localtime_r(&now, &timeinfo);
        strftime(time_data, sizeof(time_data), "%c", &timeinfo);

        //发送时间信息
        xQueueSend(Time_synchronization_Queue_Handle,
        time_data,
        0);

        xEventGroupSetBits(Oled_EventGroupHandle,OLED_TIME_SYNCHRONIZATION);


        vTaskDelay(pdMS_TO_TICKS(1000));
        

    }

}


